<?php
require_once("download_header.php");

$template->assign('stringTime', time());
$ip_addr = getIP();
$user_country = geoip_country_name_by_addr($gi, getIP());

$template->assign('script', 'download');
$template->assign('PREMIUM_LINK_UNLOCK', PREMIUM_LINK_UNLOCK);

//check if ip is banned to access this site
$isp = mysql_query("SELECT * FROM ipbans WHERE ip = '".getIP()."'");
if(mysql_num_rows($isp))
{
  die( "Your ip is banned to use this website!" );
  return;
}



$Auth2 = new Authentication;
if($Auth2->checkAuth()) // if user is logged in then assign smarty vars ..
{

	$uloggedId = $Auth2->getLoggedId();
	$user = __User::getById($uloggedId);
	if(!$user)
	{
	    die("Invalid User");
	}

	$uloggedUser = $user->username;
	$template->assign('uloggedUser', $uloggedUser);
	$template->assign('uloggedId', $uloggedId);

	$template->assign('unreads', countrUnreadMessages($uloggedUser));
	
	
}else
{

	$template->assign('uloggedUser', 0);
	$template->assign('uloggedId', 0);

}


require_once("classes/class.premium_authentication.php");

$Auth = new PremiumAuthentication;
$country = geoip_country_code_by_addr($gi, getIP());




$template->assign("SITE_NAME", SITE_NAME);
$template->assign("SITE_URL", SITE_URL);
$template->assign("SITE_KEYWORDS", urldecode(SITE_KEYWORDS));
$template->assign("SITE_DESCRIPTION", urldecode(SITE_DESCRIPTION));

$hash = substr(md5(strtotime('now').uniqid()).rand(0000000000,9999999999), rand(1,5), 25);
while(mysql_num_rows(mysql_query("SELECT * FROM offer_process WHERE code = '$hash'")))
{
    $hash = substr(md5(strtotime('now').uniqid()).rand(0000000000,9999999999), rand(1,5), 25);
}

$template->assign('randomHash', $hash);



$template->assign('ip_addr',$ip_addr);
$template->assign('user_country',$user_country);

$fileCode = safeGet($_GET['file']);
$template->assign('fileCode', $fileCode);
$template->assign('login', 0);


//set link referrer for this file
if(!isset($_SESSION[SITE_NAME.'XHSTreferrer_'.$fileCode]))
{
	if(@$_SERVER['HTTP_REFERER'] != ''){
    $_SESSION[SITE_NAME.'XHSTreferrer_'.$fileCode] = $_SERVER['HTTP_REFERER'];
	
	}else
	{
       $referrer = 'NULL';
	}
}
$referrer = makesafe($_SESSION[SITE_NAME.'XHSTreferrer_'.$fileCode]);

if(!isset($_GET['file']) || empty($fileCode))
{
	$error_msg = "Invalid file. Please use correct file link to access download page."; 
	$template->assign('error_msg', $error_msg);
	$template->display('file_error.tpl.php');
    return;	
}

//check if file exists
$fcheck_sql = mysql_query("SELECT * FROM files WHERE code = '$fileCode'");
if(!mysql_num_rows($fcheck_sql))
{
	$error_msg = "File not found."; 
	$template->assign('error_msg', $error_msg);
	$template->display('file_error.tpl.php');
    return;	
}

//update file hits
//we will use session base hits tracking, if session found, we wont update hits
if(!isset($_SESSION['HST_XFILETRACK_IkBeU_secTHSC__X'.$fileCode]))
{
  @mysql_query("UPDATE files SET hits = hits+1 WHERE code = '$fileCode'");	
  $_SESSION['HST_XFILETRACK_IkBeU_secTHSC__X'.$fileCode] = $fileCode;
}

$file_id = getFileIdByFileCode($fileCode);
$frow = mysql_fetch_object($fcheck_sql);
$filename = stripslashes($frow->filename);
$filesize = stripslashes($frow->filesize);
$filesize = convertFileSize($filesize);
$encodedname = stripslashes($frow->encodedname);
$uploader_id = $frow->uid;
$upload_type = stripslashes($frow->upload_type);
$link_url = stripslashes($frow->link_url);
$desc = stripslashes($frow->description);
//send variables to template

$filename_short = $filename;

if(strlen($filename_short) > 33)
{
   	$filename_short = substr($filename, 0, 20)."....".substr($filename, -5);
}

$template->assign('filename', $filename_short);
$template->assign('desc', $desc);
$template->assign('pagetitle', $filename);
$template->assign('filesize', $filesize);
$template->assign('upload_type', $upload_type);





$file = 'HST_USR_UPLOADED_FILES__DIR/hst_uploaded_files/'.$encodedname;
if (!file_exists($file)) {
	$error_msg = "File not found."; 
	$template->assign('error_msg', $error_msg);
	$template->display('file_error.tpl.php');
    return;	
}




//get file comments
$sql_c = mysql_query("SELECT * FROM file_comments WHERE file_id = '".makesafe($file_id)."'");
if(mysql_num_rows($sql_c))
{
	while($cr = mysql_fetch_object($sql_c))
	{
		$cm = stripslashes($cr->message);	
		$cid = $cr->id;
		$cd = date('d-m-Y', strtotime($cr->date));
		$cnm = stripslashes($cr->name);	
		$fcomments[] = array('comment' => $cm, 'date' => $cd, 'id' => $cid, 'name' => $cnm);
	}
}

$template->assign('fcomments', $fcomments);


//Get Premium Packages
$pkgsql = mysql_query("SELECT * FROM premium_packages WHERE active = 1");
if(mysql_num_rows($pkgsql))
{
	while($pkrow = mysql_fetch_object($pkgsql))
	{

     $name = stripslashes($pkrow->name);
     $period = stripslashes($pkrow->expiry_period) ." ". ucfirst(stripslashes($pkrow->period_type));
     $cost = stripslashes($pkrow->cost);	
	 $btn_id = stripslashes($pkrow->hosted_button_id);
	 
	 if(stristr($cost, "."))
	 {
	    $cost = explode(".", $cost);
		$dollars = $cost[0];
		$cents =  $cost[1];
			 
	 }else
	 {
	 	 	$dollars = $cost;
			$cents = '00';
	 }
	 
	 if(empty($btn_id))
	 continue;
	 
	 $packages[] = array('name' => $name, 'dollars' => $dollars, 'cents' => $cents, 'btn_id' => $btn_id); 
	    	
	}
	
	$template->assign('packages',$packages);
}


//Get 6 offers.
$offer_sql = mysql_query("SELECT * FROM offers WHERE (countries LIKE '%".$country."%' OR countries = 'All') AND (`hits` < `limit` OR `limit` = 0) AND active = 1 AND NOT EXISTS (SELECT * FROM offer_process WHERE  offer_process.ip = '".getIP()."' AND offer_process.offer_id = offers.id AND offer_process.status = 1) AND NOT EXISTS(SELECT * FROM banned_offers WHERE camp_id = offers.campaign_id AND network = offers.network)  ORDER BY epc DESC LIMIT 5");

if(mysql_num_rows($offer_sql)){
while($row = mysql_fetch_object($offer_sql))
{
     $offer_name = stripslashes($row->name);
	 $desc = stripslashes($row->description);
	 
	 $offers[] = array('offer_name' => $offer_name, 'id' => $row->id, 'desc' => $desc);
}
     shuffle($offers);
     $template->assign('surveys', $offers);
}



	//check if premium user logins.
  	if(isset($_POST['premium_login']))
	{
		$template->assign('login', 1);
	    $email = makesafe($_POST['email_address']);	
		$password = makesafe($_POST['password']);
		
		if(empty($email) || empty($password))
		{
		    $template->assign('login_error', 'empty username or password');	
			$template->display('download.tpl.php');
			return;
		}
        
		$password = PremiumUser::EncryptPass($email, $password);
		
		if(PremiumUser::isAccountExpired($email, $password))
		{
		    $template->assign('login_error', 'Your premium account is expired, Please buy a new premium account to enjoy straight downloads.');	
			$template->display('download.tpl.php');
			return;
			
		}
		
		$loggedId  = PremiumUser::doAuth($email, $password);
		if(!$loggedId)
		{
		    $template->assign('login_error', 'invalid login details');	
			$template->display('download.tpl.php');
			return;             			
		}
		
		
		$token = strtotime('now').md5(uniqid());
		
		while(mysql_num_rows(mysql_query("SELECT hash FROM ready_downloads WHERE hash = '$token'")))
		{
			$token = strtotime('now').md5(uniqid);
		}
		
//		$Auth->setAuth($loggedId);

        if(mysql_query("INSERT INTO ready_downloads VALUES(NULL, '$token', '$file_id', NOW(), 'premium')"))
		{
			


		$sql = mysql_query("SELECT * FROM ready_downloads WHERE hash = '$token' AND file_id = '$file_id' AND DATE(date) = CURDATE()");
		if(mysql_num_rows($sql))
		{
             
			 
			         if($upload_type == 'link')
					 {
						 
						 
				  //insert download log
				   //update downloads and download date
				 // @mysql_query("UPDATE files SET downloads = downloads+1, last_download_date = NOW() WHERE id = '$file_id'");
				  //unset($_SESSION['file_download_token_'.$fileCode]); 				  
				  
				  
				  
			      @mysql_query("INSERT INTO downloads_log VALUES(NULL, '$fileCode', '$link_url', '$download_type', '".getIP()."', NOW(), '$uploader_id', '$country', '$referrer', '$email')");
			      unset($_SESSION["referrer_$fileId"]);					  
				  
				  $template->assign('url', $link_url);
                  mysql_query("DELETE FROM ready_downloads WHERE hash = '$token'");	
				  unset($_SESSION["referrer_$fileId"]);	
				  $template->display('out.tpl.php');
				  exit;						 
						 

					  	 
					 }else{			 

			         
					  header('Content-Description: File Transfer');
					  header('Content-Type: application/octet-stream');
					  header('Content-Disposition: attachment; filename="'.$filename.'"');
					  header('Content-Transfer-Encoding: binary');
					  header('Expires: 0');
					  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
					  header('Pragma: public');
					  header('Content-Length: ' . filesize($file));
					  ob_clean();
					  flush();
					  readfile($file);
			 
					  }
 				      mysql_query("DELETE FROM ready_downloads WHERE hash = '$token'");	
					  
					  
  				     //insert download log
  				     @mysql_query("INSERT INTO downloads_log VALUES(NULL, '$fileCode', '{$SITE_URL}file/$fileCode', 'premium', '".getIP()."', NOW(), '$uploader_id', '$country', '$referrer', '$email')");
					 unset($_SESSION[SITE_NAME.'XHSTreferrer_'.$fileCode]);	
					  exit;
				  

				  

					  
			  		
		}else
		{
			$template->display('file_error.tpl.php'); //Show that file cannot download.	
		}
			


			
		}else
		{
			$template->assign('pagetitle', 'Error');
		    $template->assign('error_msg', "An error occured while setting up download, please try again or contact admin to report this error.");	
			$template->display('guest_msg.tpl.php');
		}
		
		
		
		
		
	}else if( isset($_REQUEST['token'])){

	    $token = makesafe($_REQUEST['token']);
		$sql = mysql_query("SELECT * FROM ready_downloads WHERE hash = '$token' AND file_id = '$file_id' AND DATE(date) = CURDATE()");
		if(mysql_num_rows($sql))
		{
             
			 $dr = mysql_fetch_object($sql);
		     $download_type = $dr->download_type;
					
			 //update downloads and download date
			 @mysql_query("UPDATE files SET downloads = downloads+1, last_download_date = NOW() WHERE code = '$fileCode'");

				  
				  	 
			         if($upload_type == 'link')
					 {
						 
						 
				  //insert download log
				   //update downloads and download date
				 // @mysql_query("UPDATE files SET downloads = downloads+1, last_download_date = NOW() WHERE id = '$file_id'");
				  //unset($_SESSION['file_download_token_'.$fileCode]); 				  
				  
				  
				  
			      @mysql_query("INSERT INTO downloads_log VALUES(NULL, '$fileCode', '$link_url', '$download_type', '".getIP()."', NOW(), '$uploader_id', '$country', '$referrer', '$email')");
			      unset($_SESSION[SITE_NAME.'XHSTreferrer_'.$fileCode]);					  
				  
				  $template->assign('url', $link_url);
                  mysql_query("DELETE FROM ready_downloads WHERE hash = '$token'");	
				  unset($_SESSION[SITE_NAME.'XHSTreferrer_'.$fileCode]);	
				  $template->display('out.tpl.php');
				  exit;						 
						 

					  	 
					 }else{		  
				  
						header('Content-Description: File Transfer');
						header('Content-Type: application/octet-stream');
						header('Content-Disposition: attachment; filename="'.$filename.'"');
						header('Content-Transfer-Encoding: binary');
						header('Expires: 0');
						header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
						header('Pragma: public');
						header('Content-Length: ' . filesize($file));
						ob_clean();
						flush();
						readfile($file);
						
					 }
			  

			  mysql_query("DELETE FROM ready_downloads WHERE hash = '$token'");	
			 //insert download log
			 @mysql_query("INSERT INTO downloads_log VALUES(NULL, '$fileCode', '".SITE_URL."file/$fileCode', '$download_type', '".getIP()."', NOW(), '$uploader_id', '$country', '$referrer', NULL)");
			 unset($_SESSION["referrer_$fileId"]);	
			  exit;
				  

				  
			 
					  
			  		
		}else
		{
			header("location: ".SITE_URL."file/$fileCode");
			exit;
			//$template->display('download.tpl.php');	
		}
		
		
	
		
	}elseif(isset($_POST['premium_forgot']))
	{
		
        //forgot premium password

			$template->assign('premium_forgot', 1);
			$email = makesafe($_POST['email']);
			
			
			
			if(empty($email))
			{
				if(empty($email))
				{
					$login_error = "email is empty.";
				}
				
				$template->assign('login_error', $login_error);
				$template->display("download.tpl.php");
				return;
			}
		
			$puid = getPremiumUserIdByEmail($email);
			
			if(!$puid)
			{
				$login_error = "Email address not found.";
				$template->assign('login_error', $login_error);
				$template->display("download.tpl.php");
				return;	
			}
			
			
			$sql = mysql_query("SELECT * FROM premium_accounts WHERE uid = '$puid'");
			if(!mysql_num_rows($sql))
			{
				$login_error = "Invalid User";
				$template->assign('login_error', $login_error);
				$template->display("download.tpl.php");
				return;	
			}
			
		
				 $email = getPremiumUserEmailById($puid);
				
				 $password = substr(md5(uniqid()),0,6);
				 $row = mysql_fetch_object($sql);
				 $salt = $row->code;
				 $encrypted = md5($salt.$password); 
				 


		
				 if(mysql_query("UPDATE premium_accounts SET password = '$encrypted' WHERE uid = '$puid' limit 1"))
				 {
				 
					  $mail = new Email($email, SITE_NAME.' - Premium Account Password Reset', "Hello Premium User! <br/> <br /> Your New Password: $password <br /> ".SITE_NAME, 1);
					  if($mail->sendMail())
					  {
					  $success_msg = "An email has been sent to your email address with new password.";
					  $template->assign("success_msg", $success_msg);
					  $template->assign('premium_forgot', 0);
					  $template->display("download.tpl.php");
					  }else
					  {
						$login_error = "A problem occured while sending an email to $email.";
						$template->assign('login_error', $login_error);
						$template->display("download.tpl.php");
						return;
					  }
				 }else
				 {
					  
						$login_error = "A problem occured while making new password.";
						$template->assign('login_error', $login_error);
						$template->display("download.tpl.php");
				 }
		   




		
	}else{
	
    $template->display('download.tpl.php');	
	}


?>